package JdbcTest.login;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/*
数据库连接查询程序
    1.当我们的sql语言需要传入用户输入的值时，我们需要使用PreparedStatement这个类来防止sql注入攻击，因为这个类可以预先编译sql框架，然后将
    用户输入的值传入到占位符中
    2.当需要升序降序时，可以使用Statement类

 */
public class DatabaseConnection {
    public static Connection MyConnect(){
        FileInputStream fis = null;
        Properties map = new Properties();
        Connection conn = null;
        try {
            fis = new FileInputStream("src/JdbcTest/Jdbc/DatabaseFile.properties");
            map.load(fis);
            Class c = Class.forName(map.getProperty("Driver"));
            conn = DriverManager.getConnection(map.getProperty("url"),map.getProperty("username"),map.getProperty("password"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally{
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return conn;
    }

    public static void MySelect(Connection conn,String username,String password){
        //使用PreparedStatement类防止sql注入
        PreparedStatement sta = null;
        ResultSet rs = null;
        try {
            String sql = "select * from user where username = ? and password = ?";
            //预先编译
            sta = conn.prepareStatement(sql);
            sta.setString(1,username);
            sta.setString(2,password);
            rs = sta.executeQuery();
            if(rs.next()){
                System.out.println("用户名密码验证成功！");
                System.out.println("欢迎登录系统");
            }else {
                System.out.println("用户名密码验证失败");
                System.out.println("请重新输入用户名及密码");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (sta != null) {
                try {
                    sta.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
